<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-07 15:05:42
 * @LastEditTime: 2023-02-16 10:19:33
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 递增条款
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-card :title="title">
    <template #extra>
      <a-space>
        <a-dropdown v-if="canAddIncreaseClause" placement="bottom" :trigger="['click']">
          <a-button type="text">
            <template #icon>
              <PlusCircleOutlined />
            </template>
          </a-button>
          <template #overlay>
            <a-menu @click="handleAddClick">
              <a-menu-item key="top">
                向上插入条款
              </a-menu-item>
              <a-menu-divider />
              <a-menu-item key="under">
                向下插入条款
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <a-button type="text" @click="handleRemove">
          <template #icon>
            <CloseOutlined />
          </template>
        </a-button>
      </a-space>
    </template>
    <a-form layout="vertical">
      <a-row :gutter="24" :wrap="true">
        <a-col :sm="24" :md="12" :lg="8" :xl="6">
          <a-form-item label="递增时间点" v-bind="validateInfos.incrDate">
            <a-date-picker
              style="width: 100%"
              v-model:value="modelRef.incrDate"
              :valueFormat="dateFormatStr"
              :disabled-date="disabledDate"
              :allowClear="false"
            />
          </a-form-item>
        </a-col>
        <a-col :sm="24" :md="12" :lg="8" :xl="6">
          <a-form-item label="单价递增" v-bind="validateInfos.incrPrice">
            <a-input-group compact>
              <a-input-number
                placeholder="请输入"
                v-model:value="modelRef.incrPrice"
                style="width: 60%"
                :min="0"
              />
              <a-select
                style="width: 40%"
                v-model:value="modelRef.incrPriceUnit"
              >
                <a-select-option
                  v-for="item of optionData.price_increment_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :sm="24" :md="12" :lg="8" :xl="6">
          <a-form-item label="保证金递增" v-bind="validateInfos.incrBond">
            <a-input-group compact>
              <a-input-number
                placeholder="请输入"
                v-model:value="modelRef.incrBond"
                style="width: 60%"
                :min="0"
              />
              <a-select
                style="width: 40%"
                v-model:value="modelRef.incrBondUnit"
              >
                <a-select-option
                  v-for="item of optionData.bond_increment_unit"
                  :value="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-input-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
</template>

<script>
import { defineComponent, reactive, watch, ref, computed, nextTick } from "vue";
import {CloseOutlined, PlusCircleOutlined} from "@ant-design/icons-vue";
import store from "../../../../store";
import utils from "../../../../common/utils/utils";
import moment from "moment";
import { Form } from "ant-design-vue";
import _ from "lodash";
import {useRoute} from "vue-router";
const useForm = Form.useForm;

export default defineComponent({
  name: "NormalClause",
  props: {
    index: {
      type: Number,
      default: 0,
    },
    // 触发验证
    trigger: {
      type: Number,
      default: 0,
    },
    paneFrom: {
      type: String,
      default: "default",
    },
    content: {
      type: Object,
      default: () => {
        return {};
      },
    },
    canAddIncreaseClause: {
      type: Boolean,
      default: false,
    }
  },
  components: {PlusCircleOutlined, CloseOutlined },
  setup(props, context) {
    const $route = useRoute();
    const dateFormatStr = "YYYY-MM-DD";
    const today = moment().format(dateFormatStr);
    const contractDateRange = computed(() => store.getters.contractDateRange);
    const disabledDate = (current) => {
      const { startDate, endDate } = contractDateRange.value;
      return (
        current < moment(startDate).startOf("day") ||
        current > moment(endDate).endOf("days")
      );
    };

    const title = computed(() => {
      return "递增条款" + (props.index + 1);
    });
    const modelRef = reactive({
      incrDate: today,
      incrPrice: "",
      incrPriceUnit: undefined,
      incrBond: "",
      incrBondUnit: undefined,
    });
    const rulesRef = reactive({
      incrDate: [{ required: true, message: "必填" }],
      incrPrice: [
        {
          required: true,
          validator: (rules, value) => utils.pNumberValidator(rules, value),
          trigger: "change",
        },
      ],
      incrBond: [
        {
          required: true,
          validator: (rules, value) => utils.nNumberValidator(rules, value),
          trigger: "change",
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const validateForm = () => {
      validate()
        .then(() => {
          context.emit("success", {
            type: "increase",
            content: JSON.parse(JSON.stringify(modelRef)),
          });
        })
        .catch(() => {
          context.emit("fail", {
            type: "normal",
          });
        });
    };

    const isRenewal = computed(
      () => $route.query.editType == "renewal"
    );

    const renewalDetail = computed(() => {
      if (isRenewal.value) {
        return {
          originId: $route.query.id,
          startDate: $route.query.startDate,
          endDate: $route.query.endDate,
          duration: $route.query.duration,
        }
      } else {
        return {}
      }
    });

    const setDetail = () => {
      const { content, paneFrom } = props;
      if (content) {
        if (isRenewal.value) {
          const renewalData = renewalDetail.value;
          modelRef.incrDate = renewalData.startDate;
        } else {
          modelRef.incrDate = content.incrDate || today;
        }
        modelRef.incrPrice = content.incrPrice;
        modelRef.incrPriceUnit = content.incrPriceUnit;
        modelRef.incrBond = content.incrBond;
        modelRef.incrBondUnit = content.incrBondUnit;
        nextTick(() => {
          store.dispatch("SetClauseTabChange", {
            key: paneFrom,
            changed: false,
          });
          watch(modelRef, (value) => {
            const changed =
              store.getters.clauseContentList[props.paneFrom].changed;
            if (!changed) {
              store.dispatch("SetClauseTabChange", {
                key: props.paneFrom,
                changed: true,
              });
            }
          });
        });
      }
    };

    const optionData = ref({});
    const init = () => {
      store.dispatch("ContractInit").then((res) => {
        optionData.value = res;
        if (!props.content || !props.content.incrDate) {
          setDefaultModel(res.price_increment_unit, "incrPriceUnit");
          setDefaultModel(res.bond_increment_unit, "incrBondUnit");
        }
      });
      const setDefaultModel = (list, key, id = "key") => {
        modelRef[key] = list && list.length ? list[0][id] : undefined;
      };
      setDetail();
    };

    const handleRemove = () => {
      context.emit("remove", { index: props.index, type: "increase" });
    };

    const handleAddClick = (e) => {
      const { key } = e;
      context.emit("add", {index: props.index, type: "increase", way: key});
    };

    init();

    watch(
      () => props.trigger,
      (trigger) => {
        if (trigger) {
          validateForm();
        }
      }
    );

    watch(
      () => modelRef,
      (val) => {
        context.emit("dataChange", {
          type: "increase",
          content: _.cloneDeep(modelRef),
        });
      }, {deep: true}
    );

    return {
      dateFormatStr,
      title,
      modelRef,
      validateInfos,
      optionData,
      handleRemove,
      disabledDate,
      handleAddClick,
    };
  },
});
</script>
